/**
 * http://usejsdoc.org/
 */

var express = require('express');
var router = express.Router();
var fs = require('fs');
var querystring = require('querystring');
var util = require('util');

var user4 = {
		"user4":{
			"name":"shansjlin",
			"password":"password4",
			"profession":"teacher",
			"id":4
		}
	}

router.get('/shansjlin', function(req, res) {
	res.send('restful/shansjlin');
});

router.get('/getUsers', function(req, res) {
	fs.readFile(__dirname + "./../data/userdata.json", 'utf-8', function(err, data) {
		if(err) {
			res.send("can`t get userdata.json")
		} else {
			res.send(data);
		}
	});
});

router.get('/putUsers', function(req, res) {
	fs.readFile(__dirname + "./../data/userdata.json", 'utf-8', function(err, data) {
		if(err) {
			res.send("can`t get userdata.json");
		} else {
			data = JSON.parse(data);
			data["user4"] = user4["user4"];
			res.send(JSON.stringify(data));
		}
	});
});

router.get('/deleteUsers/:id', function(req, res) {
	fs.readFile(__dirname + "./../data/userdata.json", 'utf-8', function(err, data) {
		if(err) {
			res.send("can`t get userdata.json");
		} else {
			data = JSON.parse(data);
			delete data["user" + req.params.id];
			res.send(JSON.stringify(data));
		}
		
	});
});

router.post('/postUsers', function(req, res) {
	var postdata = '';
	req.on('data', function(chunk) {
		postdata += chunk;
	});
	req.on('end', function() {
		postdata = querystring.parse(postdata);
		res.end(util.inspect(postdata)); 
		console.log("recv postdata:" + util.inspect(postdata));
	});
});

module.exports = router;